package com.project.server;

import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * 工厂类
 */
public class ServletFactory {
    private static Properties pro = new Properties();
    private static Map<String,Servlet> servletMap = new HashMap<>();
    static {
        try {
            //加载属性文件
            pro.load(new FileReader("web.txt"));

            //得到键的集合
            Set<String> keyset = pro.stringPropertyNames();
            for(String key : keyset){
                //根 据键得到值
                String value = pro.getProperty(key);
                //加载类，得到类模版
                Class c = Class.forName(value);
                servletMap.put(key,(Servlet)c.getConstructor().newInstance());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static Servlet getService(String url){

        return servletMap.get(url);
//        //根据键，得到值
//        String value = pro.getProperty(url);
//        if(value == null){//请求的是文件
//            return null;
//        }
//
//        try {
//            //加载类，得到类模版
//            Class c = Class.forName(value);
//            //产生业务组件对象
//            Object serviceObj = c.getConstructor().newInstance();
//
//            return (Servlet)serviceObj;
//
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
    }

    public static void main(String[] args) {
        Servlet s1 = getService("update");
        Servlet s2 = getService("update");
        System.out.println(s1);

        Servlet s3 = getService("add");
        Servlet s4 = getService("add");
        System.out.println(s3);
        System.out.println(s1 == s2);
        System.out.println(s3 == s4);
        System.out.println(s1 == s3);
    }
}
